package com.ebupt.migu.music.propagate.service.impl;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ebupt.migu.music.common.entity.ResultObject;
import com.ebupt.migu.music.common.exception.MyException;
import com.ebupt.migu.music.common.exception.StatusEnum;
import com.ebupt.migu.music.common.util.CSVUtils;
import com.ebupt.migu.music.common.util.DateUtil;
import com.ebupt.migu.music.propagate.mapper.PropagateApproveMapper;
import com.ebupt.migu.music.propagate.mapper.PropagateInfoMapper;
import com.ebupt.migu.music.propagate.mapper.PropagateStrategyMapper;
import com.ebupt.migu.music.propagate.pojo.dto.StrategyDto;
import com.ebupt.migu.music.propagate.pojo.dto.StrategyQueryDto;
import com.ebupt.migu.music.propagate.pojo.vo.StrategyVo;
import com.ebupt.migu.music.propagate.pojo.vo.UploadVo;
import com.ebupt.migu.music.propagate.service.PropagateApproveService;
import com.ebupt.migu.music.propagate.service.PropagateManageService;
import com.ebupt.migu.music.system.entity.SysUser;
import com.ebupt.migu.propagate.PropagateApproveInfo;
import com.ebupt.migu.propagate.PropagateInfo;
import com.ebupt.migu.propagate.PropagateStrategy;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author tz
 */
@Slf4j
@Service
public class PropagateManageServiceImpl extends ServiceImpl<PropagateStrategyMapper, PropagateStrategy> implements PropagateManageService {

    @Value("${path.propagate_upload}")
    private String uploadPath;
    @Resource
    private PropagateInfoMapper propagateInfoMapper;
    @Resource
    private PropagateApproveMapper propagateApproveMapper;
    @Resource
    private PropagateApproveService approveService;

    @Override
    public ResultObject uploadFile(MultipartFile file) {
        // 校验文件是否为空，格式是否正常
        boolean isCsv = CSVUtils.validateUploadFile(file, "csv");
        if (!isCsv) {
            throw new MyException(StatusEnum.UPLOAD, "文件格式或内容异常！");
        }
        Date date = new Date();
        // 重命名
        String filePath = uploadPath + DateUtil.parseDateToStr(date, DateUtil.DATE_TIME_FORMAT_YYYYMMDDHHMISS) + ".csv";
        //直接保存到指定目录
        CSVUtils.upload(file, filePath);
        List<String[]> strings = CSVUtils.csvRead(filePath,"UTF-8");
        UploadVo vo = UploadVo.builder().fileName(file.getOriginalFilename()).filePath(filePath)
                .fileSize(strings == null ? 0:strings.size()-1).build();
        return new ResultObject().success("文件上传成功！", vo);
    }

    @Override
    public void download(String fileName,String filePath, HttpServletResponse response) throws IOException {
        ServletOutputStream os = response.getOutputStream();
        response.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
        response.setContentType("application/x-download;charset=UTF-8");
        os.write(FileUtil.readBytes(filePath));
        os.flush();
        os.close();
    }

    @Override
    public ResultObject createOrUpdate(StrategyDto dto, SysUser sysUser) {
        // 获取策略id
        String strategyId = StringUtils.isEmpty(dto.getStrategyId()) ?
                "XF" + DateUtil.parseDateToStr(new Date(), DateUtil.DATE_TIME_FORMAT_YYYYMMDDHHMISSSSS) : dto.getStrategyId();
        // 构造参数
        PropagateStrategy ps = new PropagateStrategy();
        BeanUtils.copyProperties(dto,ps);
        ps.setStrategyId(strategyId);
        ps.setExecuteStatus(1);
        ps.setCreatorId(sysUser.getLoginName());
        ps.setCreatorName(sysUser.getUserName());
        ps.setCreatorPhone(sysUser.getMobile());
        ps.setCreatorDepartment(sysUser.getDeptName());
        // 根据类型取激活码
        if (dto.getActivationCodeType() == 1){
            // excel导入激活码，读取文件并存入redis
            List<String[]> ls = CSVUtils.csvRead(dto.getActivationCodePath());
            // 删除表头
            ls.remove(0);
            // 只取文件第一列数据
            List<String> collect = ls.stream().map(e -> e[0]).collect(Collectors.toList());
            // 激活码小于200跳过审核
            if (collect.size() < 200) {
                ps.setExecuteStatus(3);
            }
            ps.setActivationCodeKey(strategyId.concat("_ack"));
        }
        // 用户自定义数量小于200也跳过审核
        if (dto.getSendNum() < 200) {
            ps.setExecuteStatus(3);
        }
        baseMapper.createOrUpdate(ps);
        // 获取彩铃集合
        PropagateInfo pi = new PropagateInfo();
        //先删除后新增
        propagateInfoMapper.delByStrategyId(strategyId);
        dto.getRings().forEach(e -> {
            BeanUtils.copyProperties(e,pi);
            pi.setStrategyId(strategyId);
            if (e.getAddType() == 1) {
                List<String[]> l = CSVUtils.csvRead(e.getRingPath(),"UTF-8");
                // 删除表头
                l.remove(0);
                // 只取文件第一列数据
                List<String> collect = l.stream().map(s -> s[0]).collect(Collectors.toList());
                pi.setRingIds(String.join(",",collect));
            }
            propagateInfoMapper.insert(pi);
        });
        // 获取审批人集合
        PropagateApproveInfo pa = new PropagateApproveInfo();
        //先删除后新增
        propagateApproveMapper.delByStrategyId(strategyId);
        dto.getApprove().forEach(e -> {
            BeanUtils.copyProperties(e,pa);
            pa.setStrategyId(strategyId);
            propagateApproveMapper.insert(pa);
        });
        // 跳过审核的直接同步到大营销平台
        if (ps.getExecuteStatus() == 3) {
            approveService.push(ps);
        }
        return new ResultObject().success("ok");
    }

    @Override
    public ResultObject qryList(StrategyQueryDto dto) {
        Page<PropagateStrategy> page = new Page<>(dto.getPageNum(),dto.getPageSize());
        IPage<PropagateStrategy> list = baseMapper.listAll(page, dto);
        return new ResultObject().success("ok",list);
    }

    @Override
    public ResultObject qryById(Integer id) {
        PropagateStrategy ps = baseMapper.selectById(id);
        StrategyVo vo = new StrategyVo();
        Optional.ofNullable(ps).ifPresent(e -> {
            List<PropagateInfo> pi = propagateInfoMapper.qryByStrategyId(e.getStrategyId());
            List<PropagateApproveInfo> pa = propagateApproveMapper.qryByStrategyId(e.getStrategyId());
            vo.setRings(pi);
            vo.setApprove(pa);
            BeanUtils.copyProperties(e,vo);
        });
        return new ResultObject().success("ok",vo);
    }

    @Override
    public ResultObject modifyStatus(Integer id,Integer status) {
        PropagateStrategy ps = baseMapper.selectById(id);
        Optional.ofNullable(ps).ifPresent(e -> {
            e.setExecuteStatus(status);
            baseMapper.updateById(e);
        });
        return new ResultObject().success("ok");
    }
}
